// app/service/user.js
const nodemailer = require('nodemailer');
const uuid = require('uuid');
const Service = require('egg').Service;
const crypto = require('crypto');

class UserService extends Service {
  async createUser({
    nickname,
    password,
    email,
    camera,
    avatar,
  }) {
    const { ctx, app } = this;
    const user = await ctx.model.User.findOne({
      where: {
        [app.Sequelize.Op.or]: {
          nickname,
          email,
        },
      },
    });
    if (user) {
      if (user.nickname === nickname) {
        ctx.throwError({
          code: 100001,
          msg: '昵称已被使用',
        });
      } else {
        ctx.throwError({
          code: 100001,
          msg: '邮箱已被注册',
        });
      }
    }
    const row = await app.model.transaction(t => ctx.model.User.create({
      nickname,
      password: crypto.createHash('md5').update(password).digest('hex'),
      email,
      camera,
      avatar,
    }, {
      transaction: t,
    }));
    return row.dataValues.id;
  }

  async createActiveId({
    userId,
  }) {
    const activeId = uuid.v4();
    const row = await this.app.model.transaction(t => this.ctx.model.Active.create({
      id: activeId,
      userId,
    }, {
      transaction: t,
    }));
    return row.dataValues.id;
  }

  async activeUser(activeId) {
    const { ctx, app } = this;
    const acObj = await ctx.model.Active.findOne({
      where: {
        id: activeId,
        status: 0,
      },
    });
    if (acObj) {
      await app.model.transaction(async (t) => {
        await ctx.model.Active.update({
          status: 1,
        }, {
          where: {
            id: activeId,
          },
          transaction: t,
        });
        await ctx.model.User.update({
          status: 1,
        }, {
          where: {
            id: acObj.userId,
          },
          transaction: t,
        });
      });
      return true;
    }
    return null;
  }

  async login({
    username,
    password,
  }) {
    const { ctx, app } = this;
    const user = await ctx.model.User.findOne({
      where: {
        password: crypto.createHash('md5').update(password).digest('hex'),
        [app.Sequelize.Op.or]: {
          nickname: username,
          email: username,
        },
      },
      attributes: [
        ['id', 'userid'], 'nickname', 'email', 'camera', 'status', 'avatar',
      ],
    });
    if (user) {
      const { userid, nickname, email, camera, avatar, status, intro = '这个家伙很懒，什么都没有留下' } = user.dataValues;
      switch (status) {
        case 0: {
          ctx.throwError({
            msg: '账号未激活',
          });
          break;
        }
        case 2: {
          ctx.throwError({
            msg: '账号已被系统封禁',
          });
          break;
        }
        case 1: {
          return { userid, nickname, email, camera, intro, avatar };
        }
        default: {
          ctx.throwError({
            msg: '账号状态异常',
          });
        }
      }
    }
    ctx.throwError({
      msg: '账号或者密码不正确',
    });
  }

  async userinfo() {
    const { ctx } = this;
    const { userid, nickname, email, camera, avatar, status, intro } = await ctx.model.User.findOne({
      where: {
        id: ctx.session.user.userid,
      },
      attributes: [
        ['id', 'userid'], 'nickname', 'email', 'camera', 'status', 'avatar', 'intro',
      ],
    });
    return {
      userid,
      nickname,
      email,
      camera,
      status,
      intro: intro || '这个家伙很懒，什么都没有留下',
      avatar,
    };
  }

  async changeUser({
    avatar,
    camera,
    intro,
  }) {
    const { ctx } = this;
    await ctx.model.User.update({
      avatar,
      camera,
      intro,
    }, {
      where: {
        id: ctx.session.user.userid,
      },
    });
    return 0;
  }

  async email(options) {
    const mailTransport = nodemailer.createTransport(this.config.email);
    const result = await mailTransport.sendMail(options);
    return result;
  }
}

module.exports = UserService;
